"use strict";

import Vue from "vue";
import axios from "axios";
import { getToken } from "@/utils/webStorage";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent

    let token = getToken();
    if (token) {
      axios.headers["authorization"] = token;
    }
    // 接口请求头添加csrfToken字段
    axios.headers["x-csrf-token"] = getCookie("csrfToken");
    return config;
  },
  function (error) {
    // Do something with request error
    // errorState(error);

    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

// 封装获取cookie方法
const getCookie = (name) => {
  let reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  let arr = document.cookie.match(reg);
  if (arr) {
    return unescape(arr[2]);
  } else {
    return null;
  }
};

// 有登录时候开放
// const errorState = (error) => {
//   let code = error.response.status;
//   if (code == "401") {
//     Element.Message.error("长时间未操作，请重新登录");
//     delToken();
//   }
// };

Plugin.install = function (Vue) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      },
    },
    $axios: {
      get() {
        return _axios;
      },
    },
  });
};

Vue.use(Plugin);

export default Plugin;
